package io.netty.handler.codec.haproxy;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ProtocolDetectionResult;

/**
 * 扩展 负载均衡 解析
 * @author zhongbaoluo
 *
 */
public class ExtendHAProxyMessageDecoder extends ByteToMessageDecoder{

	private HAProxyMessageDecoder decoder;
	private boolean finished;
	
	public ExtendHAProxyMessageDecoder() {
		decoder = new HAProxyMessageDecoder();
	}
	
	@Override
	public boolean isSingleDecode() {
		return decoder.isSingleDecode();
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		super.channelRead(ctx, msg);
        if (finished) {
            ctx.pipeline().remove(this);
        }
	}
	
	@Override
    protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		ProtocolDetectionResult<HAProxyProtocolVersion> detectionResult = HAProxyMessageDecoder.detectProtocol(in);
		switch (detectionResult.state()) {
			case DETECTED: //发现
				decoder.decode(ctx, in, out);
				finished = true;
				break;
			case INVALID: //无效
				// 删除本节点
				finished = true;
			default:
				break; //不处理
		}
		
	}
}
